package com.qf.ssm01.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("upload")
public class UploadController {

    @RequestMapping("test1")
    @ResponseBody
    public String upload(MultipartFile source, HttpSession session) throws IOException {
        //文件的原始名称
        String filename = source.getOriginalFilename();
        //定制全局唯一的命名
        String unique = UUID.randomUUID().toString();
        //获得文件的后缀
        String ext = FilenameUtils.getExtension(filename);//abc.txt   txt    hello.html  html
        //定制全局唯一的文件名
        String uniqueFileName = unique+"."+ext;
        System.out.println("唯一的文件名:"+uniqueFileName);

        //文件的类型
        String type = source.getContentType();
        System.out.println("filename:"+filename+" type:"+type);

        String real_path = session.getServletContext().getRealPath("/upload_file");

        // 创建目录
        File file = new File(real_path);

        if(!file.exists()){ // 如果目录不存在的话，则创建
            file.mkdirs();
        }

        // 真正把文件写入服务器的方法
        source.transferTo(new File(real_path+"\\"+uniqueFileName));
        return "ok";
    }

}
